package de.sendorian.util;


import static org.apache.commons.lang.StringUtils.*;

public class StringUtils {

	public static final int TEXT_WIDTH = 100;


	public static String boxCentered(String string) {
		string = remove(string, '\n');
		return "|" + center(string, TEXT_WIDTH) + "|\n";
	}


	public static String box(String string) {
		string = remove(string, '\n');
		return "|" + rightPad(string, TEXT_WIDTH) + "|\n";
	}


	public static String boxMultiline(String string) {
		StringBuilder builder = new StringBuilder();
		for (int i = 0; i < string.length();) {
			String substring = substring(string, i, i + TEXT_WIDTH);
			int lastWordIndex = substring.lastIndexOf(' ');
			if (substring.contains("\n")) {
				lastWordIndex = substring.indexOf('\n');
			}
			if (lastWordIndex != -1) {
				substring = substring.substring(0, lastWordIndex);
				i += lastWordIndex + 1;
			} else {
				i += TEXT_WIDTH;
			}
			builder.append(box(trim(substring)));
		}
		return builder.toString();
	}


	public static String removeEmptyLines(String string) {
		if (contains(string, "\r\n")) {
			return removeEmptyLines(string, "\r\n");
		} else if (contains(string, '\n')) {
			return removeEmptyLines(string, "\n");
		} else {
			return removeEmptyLines(string, "\r");
		}
	}


	public static String removeEmptyLines(String string, String ln) {
		return removeEmptyLines(string, ln, 0);
	}


	public static String removeEmptyLines(String string, String ln, int fromIndex) {
		if (contains(string, ln)) {
			int lineBreak = string.indexOf(ln, fromIndex);
			int secondLineBreak = string.indexOf(ln, lineBreak + 1);
			if (secondLineBreak != -1) {
				String substring = string.substring(lineBreak, secondLineBreak + 1);
				if (isBlank(substring)) {
					string = replace(string, substring, ln);
					return removeEmptyLines(string, ln, string.indexOf(ln, fromIndex));
				} else {
					return removeEmptyLines(string, ln, secondLineBreak);
				}
			}
		}
		return string;
	}
}
